package com.novunda.platform.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;
import java.security.MessageDigest;


/**
 * 采用MD5加密解密
 */
public final class MD5Util {

    private static final Logger LOG = LoggerFactory.getLogger(MD5Util.class);

    private MD5Util() {
    }

    /***
     * MD5加码 生成32位md5码
     *
     * @param plainText 要加密内容
     * @return 加密后内容
     */
    public static String Md5(String plainText) {
        StringBuilder buf = new StringBuilder("");
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes(Charset.forName("UTF-8")));
            byte[] digestArray = md.digest();

            for (byte aB : digestArray) {
                int i = aB;
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(i));
            }

        } catch (Exception e) {
            LOG.error("MD5加密失败！加密信息：plainText={}", plainText, e);
        }
        return buf.toString();
    }
}